/**
 * 配置浏览器本地存储的方式，可直接存储对象数组。
 */

// import WebStorageCache from 'web-storage-cache'

type CacheType = 'localStorage' | 'sessionStorage'

export const CACHE_KEY = {
  // 用户相关
  ROLE_ROUTERS: 'roleRouters',
  USER: 'user',
  // 系统设置
  IS_DARK: 'isDark',
  LANG: 'lang',
  THEME: 'theme',
  LAYOUT: 'layout',
  DICT_CACHE: 'dictCache',
  // 登录表单
  LoginForm: 'loginForm',
  TenantId: 'tenantId'
}

// export const useCache = (type: CacheType = 'localStorage') => {
//   const wsCache: WebStorageCache = new WebStorageCache({
//     storage: type
//   })

//   return {
//     wsCache
//   }
// }

export const useCache = (type: 'localStorage' | 'sessionStorage' = 'localStorage') => {
  const set = (key: string, value: any, expired?: number) => {
    const data = {
      value,
      expired: expired ? Date.now() + expired * 1000 : undefined
    }
    if (type === 'localStorage') {
      uni.setStorageSync(key, data)
    } else {
      uni.setStorageSync(key, data)
      // 注意：uni-app 没有 sessionStorage 的概念，可以通过其他方式模拟
    }
  }

  const get = (key: string): any => {
    let data
    if (type === 'localStorage') {
      data = uni.getStorageSync(key)
    } else {
      data = uni.getStorageSync(key)
    }

    if (data && data.expired && Date.now() > data.expired) {
      remove(key)
      return null
    }
    return data?.value
  }

  const remove = (key: string) => {
    uni.removeStorageSync(key)
  }

  const clear = () => {
    uni.clearStorageSync()
  }

  return {
    wsCache: {
      set,
      get,
      remove,
      clear
    }
  }
}
export const deleteUserCache = () => {
  const { wsCache } = useCache()
  wsCache.remove(CACHE_KEY.USER)
  // wsCache.remove(CACHE_KEY.ROLE_ROUTERS)
  // 注意，不要清理 LoginForm 登录表单
}
